package org.huang.sample10.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.huang.sample10.config.support.MybatisConfigurationSupport;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * @描述：DB1Config类描述
 * @作者: huanganwei
 * @创建时间: 2021-07-31 00:43:36
 * @版本: 1.0
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = "org.huang.sample10.dal.dao.db1",
        sqlSessionFactoryRef = "db1SqlSessionFactory",
        sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DB1Config {


    @Primary // 表示这个数据源是默认数据源, 这个注解必须要加，因为不加的话spring将分不清楚那个为主数据源（默认数据源）
    @Bean("db1MybatisProperties")
    @ConfigurationProperties(prefix = "mybatis.db1") //读取application.yml中的配置参数映射成为一个对象
    public MybatisProperties db1MybatisProperties(){
        return new MybatisProperties();
    }


    @Primary // 表示这个数据源是默认数据源, 这个注解必须要加，因为不加的话spring将分不清楚那个为主数据源（默认数据源）
    @Bean("db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1") //读取application.yml中的配置参数映射成为一个对象
    public DataSource db1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory() throws Exception {
        return MybatisConfigurationSupport.sqlSessionFactoryOf(db1MybatisProperties(),db1DataSource());
    }

    @Primary
    @Bean("db1SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(db1SqlSessionFactory());
    }


    @Primary
    @Bean("db1TransactionManager")
    public PlatformTransactionManager db1TransactionManager() {
        return new DataSourceTransactionManager(db1DataSource());
    }

    @Primary
    @Bean("db1TransactionTemplate")
    public TransactionTemplate db1TransactionTemplate(){
        return new TransactionTemplate(db1TransactionManager());
    }
}
